package com.leo.javase.thread.mysql;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import org.apache.commons.lang.StringUtils;

import com.leo.javase.jdbc.db.C3P0Utils;

public class AccessDataBase {

	public static void main(String[] args) {
		int threads = 10;
		//动态参数
		if(args.length!=0 && StringUtils.isNotBlank(args[0]))
			threads = Integer.valueOf(args[0]);
		
		//创建对象
		AccessDataBase access = new AccessDataBase();
		access.init(threads);
	}
	/**
	 * 初始化方法
	 * @param threads
	 */
	public void init(int threads){
		final Access acc = new Access();
		//开启线程池
		ExecutorService pool = Executors.newFixedThreadPool(threads);
		for(int i=0; i<threads; i++){
			pool.execute(new Runnable() {
				@Override
				public void run() {
					acc.access();
				}
			});
		}
		pool.shutdown();
	}
	
}
class Access{
	private int index = 0;
	private int count = 2000;
	private int loop = 0;
	// 所对象
	private Lock lock = new ReentrantLock();
	
	private String sql = "SELECT * FROM t_access_log LIMIT ?,?";
	
	//访问数据库
	public synchronized void access(){
		try{
			Connection conn = C3P0Utils.getConnection();
			PreparedStatement ps = conn.prepareStatement(sql);
			ps.setInt(1, index);
			ps.setInt(2, count);
			System.out.println(ps.toString());
			ResultSet rset = ps.executeQuery();
			System.out.println(Thread.currentThread().getName());
			while(rset.next()){
				System.out.print(rset.getInt("id")+" ");
			}
			System.out.println();
			loop++;
			index = index + loop*2000;
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			
		}
	}
	
	
}
